#include "ContactListener.h"
#include "GameEntity.h"
#include "cocos2d.h"
#include "GameEntity.h"
#include "Player.h"
#include "Prop.h"

USING_NS_CC;

ContactListener::ContactListener()
{
}

ContactListener::~ContactListener()
{
}

void ContactListener::BeginContact(b2Contact * pContact)
{
  GameEntity * pGEA = (GameEntity *)pContact->GetFixtureA()->GetBody()->GetUserData();
  GameEntity * pGEB = (GameEntity *)pContact->GetFixtureB()->GetBody()->GetUserData();
  Player * pPlayer = NULL;
  if (pGEA && pGEA->getEntityType() == PLAYER)
  {
    pPlayer = (Player *) pGEA;
    if (pGEB)
    {
      pGEB->contactBeganWithPlayer(pPlayer, pContact);
    }
  }

  if (pGEB && pGEB->getEntityType() == PLAYER)
  {
    pPlayer = (Player *) pGEB;
    if (pGEA)
    {
      pGEA->contactBeganWithPlayer(pPlayer, pContact);
    }
  }
}

void ContactListener::EndContact(b2Contact * pContact)
{
  GameEntity * pGEA = (GameEntity *)pContact->GetFixtureA()->GetBody()->GetUserData();
  GameEntity * pGEB = (GameEntity *)pContact->GetFixtureB()->GetBody()->GetUserData();
  Player * pPlayer = NULL;
  if (pGEA && pGEA->getEntityType() == PLAYER)
  {
    pPlayer = (Player *) pGEA;
    if (pGEB)
    {
      pGEB->contactEndWithPlayer(pPlayer, pContact);
    }
  }

  if (pGEB && pGEB->getEntityType() == PLAYER)
  {
    pPlayer = (Player *) pGEB;
    if (pGEA)
    {
      pGEA->contactEndWithPlayer(pPlayer, pContact);
    }
  }
}

void ContactListener::PreSolve(b2Contact * pContact, const b2Manifold * pOldManifold)
{
}

void ContactListener::PostSolve(b2Contact * pContact, const b2ContactImpulse * pImpulse)
{
}

bool ContactListener::ShouldCollide(b2Fixture * pFixtureA, b2Fixture * pFixtureB)
{
  GameEntity * pGEA = (GameEntity *)pFixtureA->GetBody()->GetUserData();
  GameEntity * pGEB = (GameEntity *)pFixtureB->GetBody()->GetUserData();
  if (pGEA->getEntityType() == PROP)
  {
    Prop * pProp = (Prop *)pGEA;
    Player * pPlayer = (Player *) pGEB;
    pProp->usePropByPlayer(pPlayer);
    return false;
  }
  if (pGEB->getEntityType() == PROP)
  {
    Prop * pProp = (Prop *)pGEB;
    Player * pPlayer = (Player *) pGEA;
    pProp->usePropByPlayer(pPlayer);
    return false;
  }
  return true;
}
